<?php

namespace App\Cache;
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hypref_mall
 * contact  hyperf_mall@163.com
 */
class VerifyCodeCache extends Cache
{
    /**
     * 缓存key
     * @var string
     */
    public static $cacheKey = 'verify_code';       //缓存key配置常量，然后引用

    const EXPIRE_TIME = 60 * 10;

    /**
     * Notes:获取已发送验证码
     * @param string $mobile
     * @return string
     */
    public function getCode(string $mobile): ?string
    {
        $code = $this->get(static::getCacheKey($mobile));
        return empty($code) ? null : $code;
    }

    /**
     * Notes: 报错验证码
     * @param string $mobile
     * @param string $code 验证码
     * @param int $expireTime 过期时间秒
     * @return bool
     */
    public function saveCode(string $mobile, string $code,int $expireTime = self::EXPIRE_TIME): bool
    {
        //生成验证码
        // $code = random(6, '0123456789');
        if ($this->getGeneratTime($mobile,$expireTime) < 60){
            return $this->getCode($mobile);
        }
        return $this->set(static::getCacheKey($mobile), $code, $expireTime);

    }

    /**
     * Notes: 获取已生成时间
     * @param string $mobile
     * @param int $expireTime
     * @return int
     */
    public function getGeneratTime(string $mobile,int $expireTime): int
    {
        $ttlTime =  $this->ttl(static::getCacheKey($mobile));
        if (is_int($ttlTime)){
            return $expireTime- $ttlTime;
        }
        return 0;
    }


    /**
     * Notes: 删除缓存
     * @param string $mobile
     * @return int
     */
    public function remove(string $mobile): int
    {

        return $this->del(static::getCacheKey($mobile));
    }

    /**
     * Notes: 处理key
     * @param string $mobile
     * @return string
     */
    public function getCacheKey(string $mobile): string
    {
        return get_saas_id() . ':' . static::$cacheKey . ':' . $mobile;
    }
}
